"use client";
import useSWR from "swr";
import { userCenterGetCategory } from "@/apis";
import type { MenuProps } from "antd";
import {
  RobotTwo,
  Bowl,
  Makeups,
  Dog,
  Config,
  AirConditioning,
} from "@icon-park/react";
import React from "react";

export type MenuItem = Required<MenuProps>["items"][number];

// 图标映射表
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const iconMap: Record<string, React.ComponentType<any>> = {
  装备: RobotTwo,
  食品: Bowl,
  美妆: Makeups,
  宠物: Dog,
  电器: AirConditioning,
};

const fetchCategories = async (): Promise<MenuItem[]> => {
  const res = await userCenterGetCategory({ baseURL: "/api/proxy" });
  const rawCategoryList = res.data?.data || [];
  return rawCategoryList.map((category) => {
    const name = category.categoryName as string; // 断言成 string
    const IconComp = iconMap[name] || Config;
    return {
      key: `${name}`,
      label: name,
      icon: React.createElement(IconComp, {
        theme: "outline",
        size: "18",
        fill: "currentColor", // 使用 currentColor 让图标继承父元素的颜色
        style: { transition: "color 0.3s ease" }, // 添加颜色过渡效果
      }),
      children: [],
    };
  });
};

export const useCategories = () => {
  const { data, error, isLoading } = useSWR("categories", fetchCategories, {
    revalidateOnFocus: false,
    dedupingInterval: 1000 * 60 * 5,
  });

  return {
    categories: data || [],
    loading: isLoading,
    error: error ? "获取产品类别失败，请稍后重试" : null,
  };
};
